package com.woniuxy.hospital.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.hospital.hplutils.ResponseEntity;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {//自定义过滤器


    //过滤没通过进入该方法
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {

        HttpServletRequest req = (HttpServletRequest)request;
        String isAjax = req.getHeader("X-Requested-With");//获取自定义请求头
        String jwt = req.getHeader("jwt");//获取jwt
        //如果不是ajax，并且不是跨域
        if(isAjax==null && jwt==null){//如果不是Ajsx请求
            return super.onAccessDenied(request,response);//默认方法
        }

        //自定义返回JSON对象
        ResponseEntity<Void> responseEntity = new ResponseEntity<>(403,"无权限");
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(objectMapper.writeValueAsString(responseEntity));
        response.getWriter().flush();
        return false;
    }
}
